﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;



public partial class SmokersAlly_SmokersAlly : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

            if (Request.QueryString.HasKeys())
            {
                if (Request.QueryString["listid"] != String.Empty)
                    Session["listid"] = Request.QueryString["listid"];
                else
                    Session["listid"] = 1;


                if (Request.QueryString["dnis"] != null)
                {
                    Session["dnis"] = Request.QueryString["dnis"];
                }
                else
                {
                    Session["dnis"] = "9999999999";
                }

                Session["servername"] = Request.QueryString["servername"];
                Session["projectname"] = Request.QueryString["projectname"];
                Session["campaignname"] = Request.QueryString["campaignname"];
                Session["agentid"] = Request.QueryString["agentid"];
                Session["agentfirst"] = Request.QueryString["agentfirst"];
                Session["agentlast"] = Request.QueryString["agentlast"];


                Session["App"] = new DataAccess();
            }

            WebWizard.ActiveStepIndex = 0;


            lblAgentName.Text = (Session["agentfirst"].ToString() + " " + Session["agentlast"].ToString()).Trim();


        }
    }


    //POST LOGIC - For Step or Start pages
    //Add if statements as you add pages
    //For Next and Finish pages it is best to use the index in the if statements as below
    protected void WebWizard_NextButtonClick(object sender, WizardNavigationEventArgs e)
    {

        int page = WebWizard.ActiveStepIndex;
        if (page == WebWizard.WizardSteps.IndexOf(this.Intro))
        {
            //if (Session["dnis"] != "8662350260")
            //    WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(StepPageID);
            //App.PutCallData("webusercode", "P2");

            //((DataAccess)Session["App"]).PutCallData("webusercode", "P1");
        }

        //if (page == WebWizard.WizardSteps.IndexOf(this.DataCollection))
        //{
        //    ////This Switch is a sample only Please modify or delete as needed.
        //    //switch (radioMenu.SelectedValue.ToString())
        //    //{
        //    //    case "1":
        //    //        WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(Intro);
        //    //        break;
        //    //    case "2":
        //    //        WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(StepPageID);
        //    //        break;
        //    //    case "3":
        //    //        WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(FinishPageID);
        //    //        break;
        //    //    case "4":
        //    //        WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(Disposition);
        //    //        break;
        //    //    default:
        //    //        WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(Intro);
        //    //        break;
        //    //}

        //}

        if (page == WebWizard.WizardSteps.IndexOf(this.AutoShip))
        {
            Products1.loadProductTypes();
            Products1.ClearProducts();
            Products1.loadOrders();
        }
        if (page == WebWizard.WizardSteps.IndexOf(this.Products))
        {
            if (((ListBox)((Panel)Products1.FindControl("Panel1")).FindControl("lbOrderProducts")).Items.Count < 1 || lblEnterCustData.Visible)
            {
                WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(this.Disposition);
            }
        }
        if (page == WebWizard.WizardSteps.IndexOf(this.CrossSells))
        {

            if (cbFamilyPackage.Checked)
            {
                ((DataAccess)Session["App"]).PutOrderItem(119, 1);
            }

            if (cbChargerCombo.Checked)
            {
                ((DataAccess)Session["App"]).PutOrderItem(121, int.Parse(ddlChargerCombo.SelectedValue));
            }

            if (cbWallCharger.Checked)
            {
                ((DataAccess)Session["App"]).PutOrderItem(123, int.Parse(ddlWallCharger.SelectedValue));
            }

            if (cbCarCharger.Checked)
            {
                ((DataAccess)Session["App"]).PutOrderItem(124, int.Parse(ddlCarCharger.SelectedValue));
            }

            if (cbRushShipping.Checked)
            {
                ((DataAccess)Session["App"]).PutOrderItem(122, 1);
            }
        }
        if (page == WebWizard.WizardSteps.IndexOf(this.wsPreAuth))
        {
        }
        if (page == WebWizard.WizardSteps.IndexOf(this.Disposition))
        {
        }



    }

    //POST LOGIC for disposition pages
    //this is for pages that contain a disposition button
    protected void WebWizard_FinishButtonClick(object sender, WizardNavigationEventArgs e)
    {
        int page = WebWizard.ActiveStepIndex;
        //if (page == WebWizard.WizardSteps.IndexOf(this.Intro))
        //{
        //}

        //if (page == WebWizard.WizardSteps.IndexOf(this.AutoShip))
        //{
        //}

        //if (page == WebWizard.WizardSteps.IndexOf(this.Products))
        //{
        //}

        //if (page == WebWizard.WizardSteps.IndexOf(this.CrossSells))
        //{
        //}

        if (page == WebWizard.WizardSteps.IndexOf(this.wsPreAuth))
        {
            //if (btnPreAuth.Visible)
            //    WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(this.wsPreAuth);
        }

        //if (page == WebWizard.WizardSteps.IndexOf(this.Disposition))
        //{
        //}


    }

    //PRE-LOGIC
    //Add if statements as needed for post-logic
    //You can use the Step ID name instead of the index as used in Next and Finish logic.
    protected void WebWizard_ActiveStepChanged(object sender, EventArgs e)
    {


        int page = WebWizard.ActiveStepIndex;

        if (page == WebWizard.WizardSteps.IndexOf(this.Intro))
        {
            lblSelectDispo.Visible = true;
            DispoDDL1.Visible = true;
        }

        if (page == WebWizard.WizardSteps.IndexOf(this.AutoShip))
        {
            //lblTest.Text = App.GetCallData("webusercode");
            //lblTest.Text = ((DataAccess)Session["App"]).GetCallData("enterpriselistid");
            lblSelectDispo.Visible = true;
            DispoDDL1.Visible = true;
        }

        if (page == WebWizard.WizardSteps.IndexOf(this.Products))
        {
            lblSelectDispo.Visible = true;
            DispoDDL1.Visible = true;

            //((ListBox)Products1.FindControl("Panel1").FindControl("lbOrderProducts")).

            ((DataAccess)Session["App"]).RemoveOrderItem(119);
            ((DataAccess)Session["App"]).RemoveOrderItem(121);
            ((DataAccess)Session["App"]).RemoveOrderItem(122);
            ((DataAccess)Session["App"]).RemoveOrderItem(123);
            ((DataAccess)Session["App"]).RemoveOrderItem(124);

            Products1.loadOrders();
        }

        if (page == WebWizard.WizardSteps.IndexOf(this.CrossSells))
        {
            lblSelectDispo.Visible = true;
            DispoDDL1.Visible = true;

            ((DataAccess)Session["App"]).RemoveOrderItem(119);
            ((DataAccess)Session["App"]).RemoveOrderItem(121);
            ((DataAccess)Session["App"]).RemoveOrderItem(122);
            ((DataAccess)Session["App"]).RemoveOrderItem(123);
            ((DataAccess)Session["App"]).RemoveOrderItem(124);

            //if (cbAddFilter.Checked)
            //{
            //    ((DataAccess)Session["App"]).RemoveOrderItem(8);
            //}

            //if (cbCarCharger.Checked)
            //{
            //    ((DataAccess)Session["App"]).RemoveOrderItem(9);
            //}

            //if (cbCleanse.Checked)
            //{
            //    ((DataAccess)Session["App"]).RemoveOrderItem(10);
            //}

            //if (cbWhiteAss.Checked)
            //{
            //    ((DataAccess)Session["App"]).RemoveOrderItem(11);
            //}
        }

        if (page == WebWizard.WizardSteps.IndexOf(this.wsPreAuth))
        {
            lblPreAuthStatus.Text = "";
            lblSelectDispo.Visible = true;
            btnPreAuth.Visible = true;
            DispoDDL1.Visible = true;
            //((DataAccess)Session["App"]).PutCallData("webusercode", "T0");
            //calculate total cost and set to lblAmount.Text
            double amount = ((DataAccess)Session["App"]).GetOrderTotal();

            lblAmount.Text = amount.ToString();
        }

        if (page == WebWizard.WizardSteps.IndexOf(this.Disposition))
        {
            if (lblPreAuthComplete.Text == "Y")
            {
                lblDispo.Text = "Please Press F9 to Disposition";
                lblPreAuthStatus.Text = "";
                lblSelectDispo.Visible = false;
                DispoDDL1.Visible = false;
                ((DataAccess)Session["App"]).PutCallData("webusercode", "T0");

                ((DataAccess)Session["App"]).CommitOrder();
                ((DataAccess)Session["App"]).CommitCallData();
            }
            else if (lblPreAuthComplete.Text == "N")
            {
                lblDispo.Text += "<br/>NOT A SALE (NO SUCCESSFUL PREAUTH)";
            }

        }

    }

    public bool CreditPreAuth(string ccNum, string ccExp, string amount)
    {
        lblPreAuthStatus.Text = "";
        string webURL = "";

        webURL = "https://secure.networkmerchants.com/api/transact.php?type=auth&username=Smokers1&password=golfer72&ccnumber=" + ccNum + "&ccexp=" + ccExp + "&amount=" + amount;

        HttpWebRequest wrReq = (HttpWebRequest)WebRequest.Create(webURL);

        WebResponse response = wrReq.GetResponse();

        Stream receiveStream = response.GetResponseStream();

        StreamReader readStream = new StreamReader(receiveStream, System.Text.Encoding.UTF8);

        string str;
        int pos1, pos2, pos3, pos4;

        str = readStream.ReadToEnd();
        pos1 = str.IndexOf("&authcode=") + 9;
        pos2 = str.IndexOf("&transactionid=") - 1;
        pos3 = str.IndexOf("&transactionid=") + 14;
        pos4 = str.IndexOf("&avsresponse=") - 1;

        response.Close();
        readStream.Close();

        if (str.IndexOf("responsetext=Duplicate") > 0)
        {
            lblPreAuthStatus.Text += "Pre-Auth Passed<br/>";
            return true;
        }
        else
        {
            ((DataAccess)Session["App"]).PutCallData("AuthCode", str.Substring(pos1 + 1, pos2 - pos1));
            ((DataAccess)Session["App"]).PutCallData("TransactionID", str.Substring(pos3 + 1, pos4 - pos3));
            ((DataAccess)Session["App"]).PutCallData("Webresponse", str);
            ((DataAccess)Session["App"]).CommitCallData();
        }

        if (str.IndexOf("responsetext=Approved") > 0)
        {
            lblPreAuthStatus.Text += "Pre-Auth Passed<br/>";
            return true;
        }
        else
        {
            lblPreAuthStatus.Text += "Pre-Auth Failed<br/>";
            return false;
        }
    }

    public bool CreditPreAuthVoid(string transID)
    {
        lblPreAuthStatus.Text = "";
        string webURL = "";

        webURL = "https://secure.networkmerchants.com/api/transact.php?type=void&username=Smokers1&password=golfer72&transactionid=" + transID;

        HttpWebRequest wrReq = (HttpWebRequest)WebRequest.Create(webURL);

        WebResponse response = wrReq.GetResponse();

        Stream receiveStream = response.GetResponseStream();

        StreamReader readStream = new StreamReader(receiveStream, System.Text.Encoding.UTF8);

        string str;

        str = readStream.ReadToEnd();

        response.Close();
        readStream.Close();

        ((DataAccess)Session["App"]).PutCallData("VoidWebresponse", str);


        if (str.IndexOf("responsetext=Transaction Void Successful") > 0)
        {
            lblPreAuthStatus.Text += "Pre-Auth Void Success<br/>";
            ((DataAccess)Session["App"]).PutCallData("VoidWebresponse", str);
            ((DataAccess)Session["App"]).CommitCallData();
            return true;
        }
        else
        {
            if (str.IndexOf("responsetext=Only transactions pending settlement can be voided") > 0)
            {
                lblPreAuthStatus.Text += "Pre-Auth Void Success<br/>";
                return true;
            }
            else
            {
                lblPreAuthStatus.Text += "Pre-Auth Void Failed<br/>";
                return false;
            }
        }
    }

    protected void cbChargerCombo_CheckedChanged(object sender, EventArgs e)
    {
        Page.SetFocus(pnlChargerCombo);
        ToggleVisibility(ddlChargerCombo);
    }

    protected void cbWallCharger_CheckedChanged(object sender, EventArgs e)
    {
        Page.SetFocus(pnlWallCharger);
        ToggleVisibility(ddlWallCharger);
    }

    protected void cbCarCharger_CheckedChanged(object sender, EventArgs e)
    {
        Page.SetFocus(pnlCarCharger);
        ToggleVisibility(ddlCarCharger);
    }



    public void ToggleVisibility(DropDownList ddl)
    {
        if (ddl.Visible)
            ddl.Visible = false;
        else
        {
            ddl.SelectedIndex = 0;
            ddl.Visible = true;
        }
    }

    protected void btnSubmit_Click(object sender, System.EventArgs e)
    {
        lblError.Text = "";

        bool bCustValid = false;
        bool ccCheck = false;
        bool bShipValid = false;

        int result;

        bCustValid = !(string.IsNullOrEmpty(tbFirstName.Text) ||
            string.IsNullOrEmpty(tbLastName.Text) ||
            string.IsNullOrEmpty(tbAddr.Text) ||
            string.IsNullOrEmpty(tbZip.Text) ||
            string.IsNullOrEmpty(ddlCity.SelectedItem.Text) ||
            string.IsNullOrEmpty(ddlState.SelectedItem.Text) ||
            string.IsNullOrEmpty(ddlCountry.SelectedItem.Text)) &&
            (ddlCity.SelectedIndex > 0);


        ccCheck = !(string.IsNullOrEmpty(ddlCardType.SelectedItem.Text) ||
            string.IsNullOrEmpty(tbCCNumber.Text) ||
            string.IsNullOrEmpty(tbCCV.Text) ||
            string.IsNullOrEmpty(tbExpDate.Text)) &&
            (((DataAccess)Session["App"]).IsValidCC(GetCardType(ddlCardType.SelectedValue), tbCCNumber.Text)) &&
            (Int32.TryParse(tbCCV.Text, out result)) &&
            (Int32.TryParse(tbExpDate.Text, out result)) &&
            (tbExpDate.Text.Length == 4);

        

        bShipValid = !(string.IsNullOrEmpty(tbShipAddr.Text) ||
            //string.IsNullOrEmpty(tbShipaddr2.Text) ||
            string.IsNullOrEmpty(tbShipZip.Text) ||
            string.IsNullOrEmpty(ddlShipCity.SelectedItem.Text) ||
            string.IsNullOrEmpty(ddlShipState.SelectedItem.Text) ||
            string.IsNullOrEmpty(ddlShipCountry.SelectedItem.Text)) &&
            (ddlShipCity.SelectedIndex > 0) &&
            (tbShipZip.Text.Length >= 5) &&
            (tbShipZip.Text.Length <= 7);



        if (bCustValid)
        {
            ((DataAccess)Session["App"]).PutCallData("firstname", tbFirstName.Text);
            ((DataAccess)Session["App"]).PutCallData("lastname", tbLastName.Text);
            ((DataAccess)Session["App"]).PutCallData("address1", tbAddr.Text);
            if (!string.IsNullOrEmpty(tbAddr2.Text))
                ((DataAccess)Session["App"]).PutCallData("address2", tbAddr2.Text);
            else
                ((DataAccess)Session["App"]).PutCallData("address2","");
            ((DataAccess)Session["App"]).PutCallData("Zip", tbZip.Text);
            ((DataAccess)Session["App"]).PutCallData("City", ddlCity.SelectedItem.Text);
            ((DataAccess)Session["App"]).PutCallData("State", ddlState.SelectedItem.Text);
            ((DataAccess)Session["App"]).PutCallData("Country", ddlCountry.SelectedItem.Text);

            if (!cbShipping.Checked)
            {
                ((DataAccess)Session["App"]).PutCallData("ShipAddress1", tbAddr.Text);
                if (!string.IsNullOrEmpty(tbAddr2.Text))
                    ((DataAccess)Session["App"]).PutCallData("ShipAddress2", tbAddr2.Text);
                else
                    ((DataAccess)Session["App"]).PutCallData("ShipAddress2", "");
                ((DataAccess)Session["App"]).PutCallData("ShipZip", tbZip.Text);
                ((DataAccess)Session["App"]).PutCallData("ShipCity", ddlCity.SelectedItem.Text);
                ((DataAccess)Session["App"]).PutCallData("ShipState", ddlState.SelectedItem.Text);
                ((DataAccess)Session["App"]).PutCallData("ShipCountry", ddlCountry.SelectedItem.Text);
            }
            else
            {
                if (bShipValid)
                {
                    ((DataAccess)Session["App"]).PutCallData("ShipAddress1", tbShipAddr.Text);
                    if (!string.IsNullOrEmpty(tbShipAddr.Text))
                        ((DataAccess)Session["App"]).PutCallData("ShipAddress2", tbShipaddr2.Text);
                    else
                        ((DataAccess)Session["App"]).PutCallData("ShipAddress2", "");
                    ((DataAccess)Session["App"]).PutCallData("ShipZip", tbShipZip.Text);
                    ((DataAccess)Session["App"]).PutCallData("ShipCity", ddlShipCity.SelectedItem.Text);
                    ((DataAccess)Session["App"]).PutCallData("ShipState", ddlShipState.SelectedItem.Text);
                    ((DataAccess)Session["App"]).PutCallData("ShipCountry", ddlShipCountry.SelectedItem.Text);
                }
                else
                {
                    lblError.Text += "Enter Shipping Info<br/>";
                }
            }
        }
        else
        {
            if (ddlCity.Items.Count > 1)
                lblError.Text += "Select a City<br/>";
            else
                lblError.Text += "Enter Valid Customer Data<br/>";
        }

        if ((!string.IsNullOrEmpty(tbPhone.Text)) && ((tbPhone.Text.Length != 10) || !(System.Text.RegularExpressions.Regex.Match(tbPhone.Text, @"^[1-9]\d{2}[1-9]\d{6}$").Success)))
        {
            lblError.Text += "Invalid Phone<br/>";
        }
        else
        {
            if (!string.IsNullOrEmpty(tbPhone.Text))
                ((DataAccess)Session["App"]).PutCallData("PrimaryPhone", tbPhone.Text);
        }

        if ((!string.IsNullOrEmpty(tbEmail.Text)) && !((DataAccess)Session["App"]).IsValidEmail(tbEmail.Text))
        {
            lblError.Text += "Invalid Email<br/>";
        }
        else
        {
            if (!string.IsNullOrEmpty(tbEmail.Text))
                ((DataAccess)Session["App"]).PutCallData("Email", tbEmail.Text);
        }

        



        if (ddlPaymentType.SelectedIndex == 1) // debit/credit
        {
            ((DataAccess)Session["App"]).PutCallData("PaymentType", ddlPaymentType.SelectedItem.Value);

            if (ccCheck)
            {
                ((DataAccess)Session["App"]).PutCallData("CCType", ddlCardType.SelectedItem.Value);
                ((DataAccess)Session["App"]).PutCallData("CCNumber", ((DataAccess)Session["App"]).EnryptData(tbCCNumber.Text));
                ((DataAccess)Session["App"]).PutCallData("CCV", ((DataAccess)Session["App"]).EnryptData(tbCCV.Text));
                ((DataAccess)Session["App"]).PutCallData("CCExpDate", tbExpDate.Text);
            }
            else
            {
                lblError.Text += "Invalid Card Info<br/>";
            }
        }
        else
        {
            //lblError.Text += "Please select a payment method." + Environment.NewLine;
        }


        if (bCustValid)
        {
            if (ccCheck)
            {
                lblEnterCustData.Visible = false;
                Products1.Visible = true;
            }
            else
            {
                lblEnterCustData.Visible = true;
                Products1.Visible = false;
            }
        }
        else
        {
            lblEnterCustData.Visible = true;
            Products1.Visible = false;
        }


        //((DataAccess)Session["App"]).PutCallData("ShippingSame", cbShipping.Checked.ToString());


        //if (cbShipping.Checked)
        //{
        //    ((DataAccess)Session["App"]).PutCallData("ShipAddress1", tbShipAddr.Text);
        //    ((DataAccess)Session["App"]).PutCallData("ShipAddress2", tbShipaddr2.Text);
        //    ((DataAccess)Session["App"]).PutCallData("ShipCity", ddlShipCity.SelectedItem.Text);
        //    ((DataAccess)Session["App"]).PutCallData("ShipState", ddlShipState.SelectedItem.Text);
        //    ((DataAccess)Session["App"]).PutCallData("ShipZip", tbShipZip.Text);
        //    ((DataAccess)Session["App"]).PutCallData("ShipCountry", ddlShipCountry.SelectedItem.Text);
        //}
        //else
        //{
        //    ((DataAccess)Session["App"]).PutCallData("ShipAddress1", tbAddr.Text);
        //    ((DataAccess)Session["App"]).PutCallData("ShipAddress2", tbAddr2.Text);
        //    ((DataAccess)Session["App"]).PutCallData("ShipCity", ddlCity.SelectedItem.Text);
        //    ((DataAccess)Session["App"]).PutCallData("ShipState", ddlState.SelectedItem.Text);
        //    ((DataAccess)Session["App"]).PutCallData("ShipZip", tbZip.Text);
        //    ((DataAccess)Session["App"]).PutCallData("ShipCountry", ddlCountry.SelectedItem.Text);
        //}
    }


    protected void ddlPaymentType_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlPaymentType.SelectedValue == "CC")
        {
            trCCNumber.Visible = true;
            trCCType.Visible = true;
            trCCExpDate.Visible = true;
            trCCV.Visible = true;
        }
        else
        {
            trCCNumber.Visible = false;
            trCCType.Visible = false;
            trCCExpDate.Visible = false;
            trCCV.Visible = false;
        }

    }

    protected void cbShipping_CheckedChanged(object sender, EventArgs e)
    {
        if (cbShipping.Checked)
        {
            trShipAddr.Visible = true;
            trShipAddr2.Visible = true;
            trShipCity.Visible = true;
            trShipState.Visible = true;
            trShipCountry.Visible = true;
            trShipZip.Visible = true;
            trShipLbl.Visible = true;
            trShipSearchZip.Visible = true;

        }
        else
        {
            trShipAddr.Visible = false;
            trShipAddr2.Visible = false;
            trShipCity.Visible = false;
            trShipState.Visible = false;
            trShipCountry.Visible = false;
            trShipZip.Visible = false;
            trShipLbl.Visible = false;
            trShipSearchZip.Visible = false;
        }
    }

    protected void btnSearchZip_Click(object sender, EventArgs e)
    {
        ValidateZip(tbZip.Text.ToUpper(), ddlCity, ddlState, ddlCountry);
    }

    protected void btnShipSearchZip_Click(object sender, EventArgs e)
    {
        ValidateZip(tbShipZip.Text.ToUpper(), ddlShipCity, ddlShipState, ddlShipCountry);
    }

    protected void ValidateZip(string strZip, DropDownList ddl_City, DropDownList ddl_State, DropDownList ddl_Country)
    {

        ddl_City.Items.Clear();
        ddl_State.Items.Clear();
        ddl_City.Enabled = true;
        ddl_State.Enabled = true;

        if (System.Text.RegularExpressions.Regex.IsMatch(strZip.ToUpper(), @"(^\d{5}$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} +\d{1}[A-Z]{1}\d{1}$)"))
        {
            try
            {
                com.codebump.GeoPlaces g = new com.codebump.GeoPlaces();

                com.codebump.AuthenticationHeader authHeader = new com.codebump.AuthenticationHeader();
                authHeader.SessionID = "6JV2ZA4lgG1YRR+HG+JU27QWk9zI3rpRWY2iG2mzNPcdieEQXfQv0OUY0EZ+pOTxhwI1NCuF7b2oY+U/bozy0mhjFHmpaXvb";
                g.AuthenticationHeaderValue = authHeader;

                com.codebump.GeoPlaceDistance[] places = g.GetPlacesInside(strZip, "");

                for (int i = 0; i < places.Length; i++)
                {
                    com.codebump.GeoPlaceDistance place = places[i];
                    ListItem li = new ListItem(place.ToPlace, place.ToState + "," + place.ToPlace);
                    ddl_City.Items.Add(li);
                }
                if (ddl_City.Items.Count >= 1)
                {
                    ddl_State.Items.Add(ddl_City.SelectedItem.Value.Split(",".ToCharArray())[0]);
                }
                else
                {
                    ddl_State.Items.Add("");
                }
                //ddlCity.SelectedIndex = 0;

                if (System.Text.RegularExpressions.Regex.IsMatch(strZip.ToUpper(), @"(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)"))
                {
                    ddl_Country.SelectedValue = "CANADA";
                }
                else
                {
                    ddl_Country.SelectedValue = "USA";
                }

                if (ddl_City.Items.Count <= 0)
                {
                    ddl_City.Items.Add("No Cities Found");
                    ddl_State.Items.Add("No States Found");
                    ddl_City.Enabled = false;
                    ddl_State.Enabled = false;
                }
                else
                {
                    ddl_City.Items.Insert(0, "Select a City");
                    ddl_City.SelectedIndex = 0;
                    ddl_State.Enabled = false;
                }
            }
            catch
            {
                ddl_City.Items.Add("No Cities Found");
                ddl_State.Items.Add("No States Found");
                ddl_City.Enabled = false;
                ddl_State.Enabled = false;
            }
        }
        else
        {
            ddl_City.Items.Add("Invalid Zip");
            ddl_City.Enabled = false;
            ddl_State.Items.Add("Invalid Zip");
            ddl_State.Enabled = false;
        }
    }

    public DataAccess.CardType GetCardType(string cardType)
    {
        switch (cardType)
        {
            case "A":
                return DataAccess.CardType.AmericanExpress;
            case "V":
                return DataAccess.CardType.Visa;
            case "D":
                return DataAccess.CardType.Discover;
            case "M":
                return DataAccess.CardType.MasterCard;
            default:
                return DataAccess.CardType.Visa;
        }
    }
    protected void btnPreAuth_Click(object sender, EventArgs e)
    {
        bool ccCheck;
        int result;

        ccCheck = !(string.IsNullOrEmpty(ddlCardType.SelectedItem.Text) ||
            string.IsNullOrEmpty(tbCCNumber.Text) ||
            string.IsNullOrEmpty(tbCCV.Text) ||
            string.IsNullOrEmpty(tbExpDate.Text)) &&
            (((DataAccess)Session["App"]).IsValidCC(GetCardType(ddlCardType.SelectedValue), tbCCNumber.Text)) &&
            (Int32.TryParse(tbCCV.Text, out result)) &&
            (Int32.TryParse(tbExpDate.Text, out result)) &&
            (tbExpDate.Text.Length == 4);

        if (ccCheck)
        {
            if (CreditPreAuth(tbCCNumber.Text, tbExpDate.Text, lblAmount.Text))
            {
                lblPreAuthComplete.Text = "Y";
                btnPreAuth.Visible = false;
                btnVoidPreAuth.Visible = true;

                cbStarterKit.Visible = false;
                lblPreAuthFailed.Visible = false;
            }
            else
            {
                lblPreAuthComplete.Text = "N";
                btnPreAuth.Visible = true;
                btnVoidPreAuth.Visible = false;

                if (cbStarterKit.Visible == true) //already attempted starter package, pre auth still failed. can't dispo as sale
                {
                    WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(this.Disposition);
                    lblDispo.Text += "<font color='red'>SECOND PREAUTH FAILED<font/><br/>";
                    cbStarterKit.Visible = false;
                }
                else //first pre auth attempt (no starter package attempted yet)
                {
                    btnPreAuth.Visible = false;
                    cbStarterKit.Visible = true;
                }

                lblPreAuthFailed.Visible = true;
            }

        }
        else
        {
            lblError.Text += "Invalid CC Number<br/>";
        }
    }
    protected void btnVoidPreAuth_Click(object sender, EventArgs e)
    {
        if (CreditPreAuthVoid(((DataAccess)Session["App"]).GetCallData("TransactionID")))
        {
            lblPreAuthComplete.Text = "N";
            btnPreAuth.Visible = true;
            btnVoidPreAuth.Visible = false;
        }
        else
        {
            lblPreAuthComplete.Text = "Y";
            btnPreAuth.Visible = false;
            btnVoidPreAuth.Visible = true;
        }
    }
    protected void cbStarterKit_CheckedChanged(object sender, EventArgs e)
    {
        if (cbStarterKit.Checked)
        {
            //((DataAccess)Session["App"])
            lblPreAuthFailed.Visible = false;

            int prevOrderID = Int32.Parse(((ListBox)Products1.FindControl("Panel1").FindControl("lbOrderProducts")).Items[0].Value);

            ((DataAccess)Session["App"]).RemoveOrderItem(prevOrderID);

            Products1.SetOrderType("8");
            Products1.loadProductTypes();
            Products1.ClearProducts();
            Products1.loadOrders();

            WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(this.Products);
        }
        
    }
}